<template>
  <div  class="container-wrapper" :class="[customClass]">
    <div>
      <draggable 
        :list="data"
        item-key="fieldId" 
        :group="{name: 'dragGroup', pull: 'clone', put: false}"
        ghost-class="ghost"
        handle=".transition-group-el"
        filter=".forbid"
        dragClass="dragClass"
        chosen-class="chosenClass"
        animation="300"
      >
        <template #item="{ element: widget, index }">
          <div class="transition-group-el" @click="selectField(widget.fieldId)" style="display: inline-block;margin-left:5px">
             <dragButton :data="widget" @remove="remove"></dragButton>
          </div>
        </template>
      </draggable> 
     </div>
     <div class="container-action" v-if="true">
        <i title="添加组件" @click.stop="add">
           <Plus style="width: 1em; height: 1em; margin-right: 3px" />
        </i>
      </div>
  </div>
</template>

<script setup lang="ts">
  import { reactive, toRefs, watch} from 'vue'
  import draggable from "vuedraggable"
  import {nanoid} from 'nanoid'
  import {Plus} from '@element-plus/icons-vue';
  import dragButton from './dragButton.vue'

  const parentData = defineProps({
      data:Array
  });

  function add(){
    let fieldId= nanoid();
    parentData.data.push(
      {fieldId: fieldId, type: 'button',  name:'新操作'}
    );
  }

  function remove(fieldId){
      let removeIndex = parentData.data.findIndex(item => {
          if (item.fieldId == fieldId) {
              return true
          }
      })
      parentData.data.splice(removeIndex, 1);
  }


  const emits = defineEmits(['selected']);
  function selectField(fieldId){
      let index = parentData.data.findIndex(item => {
          if (item.fieldId == fieldId) {
              return true
          }
      })
      let item= parentData.data[index];
      emits('selected',item);
  }

</script>

<style lang="scss" scoped>
  .container-wrapper {
    position: relative;
    margin-bottom: 5px;

    .container-action{
      position: absolute;
      //bottom: -30px;
      bottom: 2px;
      right: 2px;
      height: 28px;
      line-height: 28px;
      background: #409EFF;
      z-index: 999;

      i {
        font-size: 18px;
        color: #fff;
        margin: 0 5px;
        cursor: pointer;
      }
    }
  }

 
</style>
